import { MARK_COLUMN_OBJ, MARK_FIELD_DEFAULT, MARK_FIELD_SET } from '@/utils/constant';
import { FC, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { getMarkFieldOption, MessageWaring } from '@/utils/tool';
import { Modal, message, Checkbox } from 'antd';
import { Storage } from '@/utils/storage';
import { useStores } from '@/stores';
import './index.less';

const fieldCheckAllList = getMarkFieldOption(MARK_FIELD_SET);

export interface FlawDetailConf {
  onRef: Ref<any> | undefined;
  onSubmit: (labelInfo: any) => void;
  type?: string;
}

const CheckboxGroup = Checkbox.Group;
const MarkingField: FC<FlawDetailConf> = (FlawDetailProps: FlawDetailConf) => {
  const { markingStore } = useStores();
  const [filedDialog, setFiledDialog] = useState(false);
  const [checkedList, setCheckedList] = useState<string[]>([]);

  useEffect(() => {
    try {
      const isStorage = Storage.get('markingField');
      let checkedList: Array<string> = [];
      if (isStorage) {
        checkedList = isStorage.checkedList;
      } else {
        checkedList = MARK_FIELD_DEFAULT;
      }
      setCheckedList(checkedList);
    } catch (error) {
      console.log('error', error);
    }
  }, []);

  // 点击-确定
  const handleSelect = async () => {
    if (!checkedList.length) {
      MessageWaring('字段设置不能为空，请重新设置！');
      return;
    }
    Storage.set('markingField', { checkedList: checkedList }); // marking字段设置
    markingStore.setMarkField(checkedList, MARK_COLUMN_OBJ);
    FlawDetailProps.onSubmit(checkedList);
  };

  const onChange = (list: string[]) => {
    setCheckedList(list);
  };

  // 给外部调用
  useImperativeHandle(FlawDetailProps.onRef, () => ({
    setShowFiledDialog(val: boolean | ((prevState: boolean) => boolean)) {
      setFiledDialog(val);
    }
  }));

  return (
    <Modal
      title="字段设置"
      open={filedDialog}
      onOk={handleSelect}
      width={800}
      onCancel={() => {
        setFiledDialog(false);
      }}
      wrapClassName="fieldSetDialog"
    >
      <CheckboxGroup options={fieldCheckAllList} value={checkedList} onChange={onChange} />
    </Modal>
  );
};
export default MarkingField;
